angular.module('statApp', ['Common', 'Chart'])
	/**
	 * 主控制器
	 */
	.controller('statCtrl', ['$rootScope', '$scope', '$q', 'SearchForm', 'API', 'Loading',
		function($rootScope, $scope, $q, SearchForm, API, Loading) {
			var cfg = window.app && window.app.config || {};
			cfg.api = cfg.api || (location.origin + location.pathname);
			var tabs;
			$scope.tabs = tabs = {
				list: 1,
				chart: 2,
				test : 9999,
			};
			$scope.showTab = function(tab) {
				$scope.currTab = tab;
			};
			$scope.getTabClass = function(tab) {
				return $scope.currTab === tab ? 'on' : 'off';
			};
			// 默认显示"详细记录"Tab
			$scope.showTab(tabs.list);
			// 请求数据
			$scope.fetchData = function(_params) {
				var defer = $q.defer();
				//显示遮罩层
				Loading.show();
				// 获取搜索表单中输入的参数
				var params = SearchForm.getParams();
				// 填充参数(替换表单中的参数)
				for (var x in _params) {
					params[x] = _params[x];
				};
				// 请求API
				API.fetch(cfg.api, params).then(function(rtn) {
					defer.resolve(rtn); // 成功时通知调用者解决
				}).catch(function(error) { // 失败时处理
					if (error.msg) {
						alert(error.msg);
					}
				}).finally(function() { // 无论成功或失败的处理
					Loading.hide();
				});
				return defer.promise;
			};
		}
	])
	/**
	 * 统计图表控制器
	 */
	.controller('chartCtrl', ['$rootScope', '$scope', 'SearchForm', 'ChartDelegate',
		function($rootScope, $scope, SearchForm, ChartDelegate) {
			var params = {
				type: 'chart',
			};

			function fetchData() {
				$scope.fetchData(params).then(function(data) {
					if (!data.chart) {
						return false;
					}
					// 重新生成图表
					var options = data.chart;
					options.tooltip = {
						trigger: 'axis',
					};
					options.toolbox = {
						feature: {
							magicType: {
								type: ['line', 'bar']
							},
							restore: {},
							saveAsImage: {},
							dataView: {},
						},
						right:'200px',
					};
					ChartDelegate.getInstanceById('main').setOption(options);
					// 统计数据
					$scope.statData = data.stat || [];
					// 计算表格数据
					var thItems = [],
						tdList = [];
					var totalRows = options.xAxis.data.length;
					var seriesCount = options.series.length;
					thItems.push(options.xAxis.name);
					for (var i = 0; i < seriesCount; i++) {
						thItems.push(options.series[i].name);
					}
					for (var i = 0; i < totalRows; i++) {
						var row = [];
						row.push(options.xAxis.data[i]);
						for (var j = 0; j < seriesCount; j++) {
							row.push(options.series[j].data[i]);
						}
						tdList.push(row);
					}
					$scope.thItems = thItems;
					$scope.tdList = tdList;

				});
			};
			SearchForm.onSubmit(function() {
				fetchData();
			});
			fetchData();
		}
	])
	/**
	 * 详细记录控制器
	 */
	.controller('listCtrl', ['$scope', 'SearchForm', 'API', function($scope, SearchForm, API) {
		// 请求的参数
		var params;
		$scope.params = params = {
			type: 'list',
			order: 'id',
			sort: 0,
			page: 1,
			pagesize: 20,
		};
		var config  = window.app && window.app.config || {};
		$scope.thItems = config.thItems || [];
		$scope.tdClass = config.tdClass || {};

		function fetchData() {
			// console.trace('listCtrl.fetchData.params', params);
			$scope.fetchData(params).then(function(data) {
				if ( data.list===undefined ) {
					return false;
				}
				$scope.list = data.list;
				if ( data.total !== undefined ) {
					$scope.totalRows = data.total;
				}
			});
		};

		$scope.onParamsChange = function(_params){
			params.order = _params.order;
			params.sort  = _params.sort;
			params.page  = _params.page;
			params.pagesize = _params.pagesize;
			fetchData();
		}
		// 注册"搜索表单点击提交"时的回调函数
		SearchForm.onSubmit(function() {
			params.page = 1;
			fetchData();
		});
		fetchData();
	}])
	/**
	 * 测试控制器
	 */
	.controller('testCtrl', ['$scope', function($scope){

	}])
	/**
	 * 表单服务
	 */
	.factory('SearchForm', ['$rootScope', function($rootScope) {
		var elForm = document.getElementById('searchForm');
		var onSubmitCallbacks = [];
		elForm.onsubmit = function() {
			onSubmitCallbacks.forEach(function(callback) {
				callback();
			});
			return false;
		}


		var eDownExcelBtn = document.getElementById('downExcelBtn');
		if(eDownExcelBtn){
			eDownExcelBtn.onclick = angular.noop;
			eDownExcelBtn.addEventListener('click',function(){
				console.log(elForm);
				var query = jQuery(elForm).serialize();

				var url = location.href + (location.href.indexOf('?')>=0 ? '&' : '?') + 'downExcel=1&'+query;
				eDownExcelBtn.href = url;
			});
		}
		




		var self = {
			onSubmit: function(callback) {
				onSubmitCallbacks.push(callback);
			},
			getParams: function() {
				var params = {};
				$(elForm).serializeArray().forEach(function(item) {
					params[item.name] = item.value;
				});
				return params;
			},
		};

		return self;
	}])